package cn.wizzer.app.task.commons.ext.quartz.job;

import cn.wizzer.app.crown.modules.models.CrownMatch;
import cn.wizzer.app.crown.modules.models.enums.MatchTypeEnum;
import cn.wizzer.app.crown.modules.services.CrownConfigService;
import cn.wizzer.app.crown.modules.services.CrownMatchService;
import cn.wizzer.app.crown.modules.services.result.BKMatchResultService;
import cn.wizzer.app.crown.modules.services.result.FTMatchResultService;
import cn.wizzer.app.crown.modules.models.CrownConfig;
import cn.wizzer.app.sys.modules.models.SysMsg;
import cn.wizzer.app.sys.modules.services.SysMsgService;
import cn.wizzer.notify.WkNotifyUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.List;

/**
 * 获取赛事赛果
 */
@IocBean
public class CrownJobMatchResult implements Job {
    @Inject
    @Reference(retries = 3, timeout = 500000)
    private CrownMatchService matchService;

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private FTMatchResultService ftMatchResultService;

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private BKMatchResultService bkMatchResultService;

    @Inject
    @Reference(retries = 3, timeout = 500000)
    private CrownConfigService crownConfigService;

    @Inject
    @Reference
    private SysMsgService sysMsgService;

    @Inject
    @Reference
    private WkNotifyUtil wkNotifyUtil;

    private static final Log log = Logs.get();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        CrownConfig crownConfig = crownConfigService.syncOne("获取赛果任务");
        if (crownConfig != null) {
            log.info("准备开始赛事赛果爬取:" + crownConfig);
            this.crawler(crownConfig, jobExecutionContext);
        }
    }

    private synchronized void crawler(CrownConfig crownConfig, JobExecutionContext context) {
        try {
            // 获取系统当前时间
            String endTime = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            // 获取未结束的赛事
            Cnd cnd = Cnd.where("date_time", "<", endTime).and("stage", "!=", "finished")
                    .and("stage", "!=", "other").limit(0, 500);
            List<CrownMatch> list = matchService.query(cnd);
            for (int i = 0; i < list.size(); i++) {
                try {
                    if (MatchTypeEnum.FOOTBALL.equals(list.get(i).getType())) {
                        ftMatchResultService.crawler(list.get(i), crownConfig);
                    } else if (MatchTypeEnum.BASKETBALL.equals(list.get(i).getType())) {
                        bkMatchResultService.crawler(list.get(i), crownConfig);
                    }
                } catch (RuntimeException e) {
                    String content = e.toString();
                    log.error("爬取赛果RuntimeException异常：" + content);
                    if (content.contains("BizException")) {
                        this.sentMsg(content);
                    }
                }
            }
        } catch (Exception e) {
            log.error("爬赛果定时任务异常" + e.getMessage());
        } finally {
            // 获取账号，判断是否为空，以防账号已经被清除
            crownConfigService.release(crownConfig);
        }
    }

    /**
     * 将爬取到的错误赛果发送到后台消息
     *
     * @param content
     */
    private void sentMsg(String content) {
        content = content.substring(content.indexOf("{remand='") + 9, content.lastIndexOf("'}"));
        log.error(content);
        String title = "爬取赛果比分校验错误:" + content.split("&&")[0];
        content = content.split("&&")[1];
        // 赛果校验错误后台要发通知
        //构建消息通知
        log.error("爬取赛果异常，准备给后台发送消息，标题："+ title + "，内容" + content);
        SysMsg msg = sysMsgService.createMsg("system", title, content, null);
        //插入通知
        sysMsgService.saveMsg(msg, null);
        //后台通知管理员
        wkNotifyUtil.notify(msg, null);
    }

}
